<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MQTT Web Client</title>
    {# <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script> #}
    <script src="{{ url_for('static', filename='js/mqtt.min.js') }}"></script>
</head>
<body>
    <h1>实时数据监测</h1>

    <div>当前在线数量: <span id="online_count">0</span></div>
    <div>当前离线数量: <span id="offline_count">0</span></div>
    <div id="sensor_data">

        <table border="1">

            <thead>
                <tr>

                    <th>序号</th>
                    <th>支架号</th>
                    <th>站点MAC</th>
                    <th>传感器类型</th>
                    <th>传感器MAC</th>
                    <th>类型</th>
                    <th>在线状态</th>
                    <th>提交时间</th>
                    <th>数据</th>
                    <th>解析结果</th>
                    


                </tr>
            </thead>
            <tbody>
                {% for group_data in xlsx_info['group_data_list'] %}

                <!-- group_data is a dict, for example: 
                    {
                        'group_id': 1, 
                        'bracket_number': 7, 
                        'station_mac': '0100', 
                        'sensor_list': [
                            {
                                'sensor_type': 'A', 
                                'sensor_mac': '010A', 
                                'sensor_type_name': '倾角', 
                                'online_status': 'offline', 
                                'update_time': None, 
                                'row_data': None, 
                                'parse_result': None,
                                'parse_result': None, 
                                'total_upload_times': None, 
                                'interrupted_times': None, 
                                'should_upload_times': None
                            }
                        ] -->

                {% for sensor_data in group_data['sensor_list'] %}
                <tr>
                    
                        {% if loop.index0==0 %}
                        <td rowspan="5">{{group_data['group_id']}}</td>
                        <td rowspan="5">{{group_data['bracket_number']}}</td>
                        <td rowspan="5">{{group_data['station_mac']}}</td>
                        {% endif %}
                    
                        <td>{{sensor_data['sensor_type']}}</td>
                        {# <td>{{sensor_data['sensor_mac']}}</td> #}
                        <td><a href="{{ url_for('sensor_data', sensor_mac=sensor_data['sensor_mac']) }}" target="_blank">{{sensor_data['sensor_mac']}}</a></td>

                        <td>{{sensor_data['sensor_type_name']}}</td>

                        <!-- <td style="{% if sensor_data['online_status'] == 'online' %}background-color: green;{% elif sensor_data['online_status'] == 'offline' %}background-color: white;{% else %}background-color: red;{% endif %}">{{ sensor_data['online_status'] }}</td> -->
                        <!-- <td>{{sensor_data['update_time']}}</td>
                        <td>{{sensor_data['row_data']}}</td>
                        <td>{{sensor_data['parse_result']}}</td> -->

                        <td id="{{sensor_data['sensor_mac']}}_online_status"></td>
                        <td id="{{sensor_data['sensor_mac']}}_update_time"></td>
                        <td id="{{sensor_data['sensor_mac']}}_row_data"></td>
                        <td id="{{sensor_data['sensor_mac']}}_parse_result"></td>



                    
                </tr>
                {% endfor %}

                {% endfor %}
            </tbody>
        </table>

    </div>


    <div id="message"></div>

    <script>


        var sensor_mac_list = [
                "010A","010B","010C","010D","010E",
                "020A","020B","020C","020D","020E",
                "030A","030B","030C","030D","030E",
                "040A","040B","040C","040D","040E",
                "050A","050B","050C","050D","050E",
                "060A","060B","060C","060D","060E",
                "070A","070B","070C","070D","070E",
                "080A","080B","080C","080D","080E",
                "090A","090B","090C","090D","090E",
                "100A","100B","100C","100D","100E",
                "110A","110B","110C","110D","110E",
                "120A","120B","120C","120D","120E",
                "130A","130B","130C","130D","130E",
                "140A","140B","140C","140D","140E",
                "150A","150B","150C","150D","150E",
                "160A","160B","160C","160D","160E",
                "170A","170B","170C","170D","170E",
                "180A","180B","180C","180D","180E",
                "190A","190B","190C","190D","190E",
                "200A","200B","200C","200D","200E",
                "210A","210B","210C","210D","210E",
                "220A","220B","220C","220D","220E",
                "230A","230B","230C","230D","230E",
                "240A","240B","240C","240D","240E",
                "250A","250B","250C","250D","250E",
                "260A","260B","260C","260D","260E",
                "270A","270B","270C","270D","270E",
                "280A","280B","280C","280D","280E",
                "290A","290B","290C","290D","290E",
                "300A","300B","300C","300D","300E",
            ]

        // MQTT Broker URL and port
        // 获取当前页面的 URL 并解析出 WebSocket URL




        const url = window.location.href;
        const host = url.split('/')[2];
        const port = 9001;
        
        const brokerUrl = `ws://${host}:${port}`.replace(':5000', ''); // WebSocket URL for MQTT
        // const brokerUrl = 'ws://localhost:9001'; // WebSocket URL for MQTT
        console.log('WebSocket URL:', brokerUrl);
        const topicSubscribe = 'iot/devices/test/baina/allinone/ws';

        // Create a client instance
        const client = mqtt.connect(brokerUrl);

        client.on('connect', function () {
            console.log('Connected to MQTT Broker');
            client.subscribe(topicSubscribe, function (err) {
                if (!err) {
                    console.log('Subscribed to topic:', topicSubscribe);
                } else {
                    console.error('Failed to subscribe to topic:', err);
                }
            }, qos=1);
        });

        client.on('message', function (topic, message) {
            // message is Buffer
            const messageStr = message.toString();
            console.log('Received message:', messageStr);

            

            // // 创建一个新的 <p> 标签
            // const newParagraph = document.createElement('p');
            // newParagraph.innerText = messageStr;

            // // 将新的 <p> 标签添加到 <div id="message"> 中
            // document.getElementById('message').appendChild(newParagraph);

            // 解析 JSON 数据
            const jsonData = JSON.parse(messageStr);

            // {"start_character": "e5", "len": 27, "sn": 0, "command_type": "sensor_info", "devaddr": "0102", "rssi": 36, "date": "2063-3-7 14:0:0", "dev_type": "\u503e\u89d2", "sensor_value": {"front_and_rear_pitch_angle": 76.8, "left_and_right_tilt_angle": 161.6}, "battery_percentage": "0 %", "sensor_light": "01", "firmware_version": "01", "hardware_version": "00", "number_of_abnormal": "fe", "abnormals": "5e"}

            // devaddr 设备地址就是传感器 MAC 地址
            const sensorMac = jsonData.devaddr.toUpperCase(); // 大写字母

            if (!sensor_mac_list.includes(sensorMac)) {
                // 忽略广播数据
                console.log('Ignore broadcast data');
                return;
            }

            // 更新传感器在线状态
            const onlineStatus = document.getElementById(sensorMac + '_online_status');
            onlineStatus.innerText = "在线";
            onlineStatus.style.backgroundColor = "green";


            // 更新传感器更新时间
            const updateTime = document.getElementById(sensorMac + '_update_time');
            // 当前时间
            const now = new Date();
            // 格式化时间 字符串 2021/11/11 11:11:11
            const formattedTime = now.toLocaleString();
            updateTime.innerText = formattedTime;

            // 更新传感器数据 
            // const rowData = document.getElementById(sensorMac + '_row_data');
            // rowData.innerText = JSON.stringify(jsonData.sensor_value);

            // 更新传感器解析结果
            const parseResult = document.getElementById(sensorMac + '_parse_result');
            parseResult.innerText = messageStr;
            
        });

        client.on('error', function (err) {
            console.error('MQTT Error:', err);
            client.reconnect();
        });

        // 在线状态更新 定时器: 如果最后更新时间超过 3 分钟，则更新为离线状态

        const updateOnlineStatusInterval = setInterval(function () {

            var online_count = 0;
            var offline_count = 0;

            for (let i = 0; i < sensor_mac_list.length; i++) {
                const sensorMac = sensor_mac_list[i];
                const updateTime = document.getElementById(sensorMac + '_update_time');
                if (updateTime.innerText == "") {
                    // 还没有更新过数据，跳过
                    const onlineStatus = document.getElementById(sensorMac + '_online_status');
                    onlineStatus.innerText = "离线";
                    onlineStatus.style.backgroundColor = "red";
                    offline_count = offline_count + 1;
                    continue;
                }
                const now = new Date();
                const lastUpdateTime = new Date(updateTime.innerText);
                const diffTime = (now - lastUpdateTime) / 1000; // 单位：秒
                if (diffTime > 180) { // 超过 3 分钟
                    const onlineStatus = document.getElementById(sensorMac + '_online_status');
                    onlineStatus.innerText = "离线";
                    onlineStatus.style.backgroundColor = "red";
                    offline_count = offline_count + 1;
                }
                else {
                    online_count = online_count + 1;
                }
            }

            // 更新在线数量
            document.getElementById("online_count").innerText = online_count;
            document.getElementById("offline_count").innerText = offline_count;
        }, 5000); // 每隔 5 秒更新一次
    </script>
</body>
</html>
